

package net.jjjshop.shop.controller.order;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.jjjshop.common.entity.order.Order;
import net.jjjshop.common.entity.order.OrderCreditPay;
import net.jjjshop.common.entity.order.OrderProduct;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.common.enums.OrderPayTypeEnum;
import net.jjjshop.common.service.order.OrderCreditPayService;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.common.util.OrderUtils;
import net.jjjshop.common.util.alimini.AlipayUtils;
import net.jjjshop.common.util.buer.BuerUtil;
import net.jjjshop.framework.common.api.ApiResult;
import net.jjjshop.framework.log.annotation.OperationLog;
import net.jjjshop.framework.util.UUIDUtil;
import net.jjjshop.shop.param.order.*;
import net.jjjshop.shop.service.order.OrderService;
import net.jjjshop.shop.vo.order.OrderVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(value = "订单管理", tags = {"I-后台-订单管理"})
@RestController
@RequestMapping("/shop/order/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderCreditPayService orderCreditPayService;
    @Autowired
    private AlipayUtils alipayUtils;
    @Autowired
    private UserService userService;


    @RequestMapping(value = "/index", method = RequestMethod.POST)
    @RequiresPermissions("/order/order/index")
    @OperationLog(name = "index")
    @ApiOperation(value = "订单列表(新增字段人脸识别,身份证等字段,订单审核状态)", response = String.class)
    public ApiResult<Map<String,Object>> index(@Validated @RequestBody OrderPageParam orderPageParam) throws Exception{
        Map<String,Object> result = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        /**
         * 查询条件：订单状态:authstr待审核,tomorrowExpire:明日到期,
         * todayExpire:今日到期,overdue:已逾期,overdueAlreadyPaid:已逾期已还款
         */
        jsonObject.put("all", orderService.getCount("all"));
        jsonObject.put("comment", orderService.getCount("comment"));
        jsonObject.put("six", orderService.getCount("six"));
        jsonObject.put("payment", orderService.getCount("payment"));
        jsonObject.put("delivery", orderService.getCount("delivery"));
        jsonObject.put("received", orderService.getCount("received"));
        jsonObject.put("authstr", orderService.getCount("authstr"));
        jsonObject.put("tomorrowExpire", orderService.getCount("tomorrowExpire"));
        jsonObject.put("todayExpire", orderService.getCount("todayExpire"));
        jsonObject.put("overdue", orderService.getCount("overdue"));
        jsonObject.put("overdueAlreadyPaid", orderService.getCount("overdueAlreadyPaid"));
        jsonObject.put("noPass", orderService.getCount("noPass"));
        result.put("orderList", orderService.getList(orderPageParam));
        result.put("orderCount", jsonObject);
        result.put("deliveryList", orderService.getDeliveryList());
        return ApiResult.ok(result);
    }

    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    @RequiresPermissions("/order/order/detail")
    @OperationLog(name = "detail")
    @ApiOperation(value = "detail", response = String.class)
    public ApiResult<OrderVo> detail(Integer orderId) throws Exception{
        return ApiResult.ok(orderService.detail(orderId));
    }

    //修改订单价格
    @RequestMapping(value = "/updatePrice", method = RequestMethod.POST)
    @RequiresPermissions("/order/order/updatePrice")
    @OperationLog(name = "updatePrice")
    @ApiOperation(value = "updatePrice", response = String.class)
    public ApiResult<String> updatePrice(@Validated @RequestBody OrderPriceParam orderPriceParam){
        if (orderService.updatePrice(orderPriceParam)) {
            return ApiResult.ok(null, "修改成功");
        } else {
            return ApiResult.fail("修改失败");
        }
    }

    @RequestMapping(value = "/delivery", method = RequestMethod.POST)
    @RequiresPermissions("/order/order/delivery")
    @OperationLog(name = "delivery")
    @ApiOperation(value = "delivery", response = String.class)
    public ApiResult<String> delivery(@Validated @RequestBody OrderParam orderParam) throws Exception{
        if (orderService.delivery(orderParam)) {
            return ApiResult.ok(null, "发货成功");
        } else {
            return ApiResult.fail("发货失败");
        }
    }

    @RequestMapping(value = "/orderCancel", method = RequestMethod.POST)
    @RequiresPermissions("/order/operate/confirmCancel")
    @OperationLog(name = "orderCancel")
    @ApiOperation(value = "orderCancel", response = String.class)
    public ApiResult<String> orderCancel(@Validated @RequestBody OrderCancelParam orderCancelParam) throws AlipayApiException {
        if (orderService.orderCancel(orderCancelParam)) {
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderCancelParam.getOrderNo()));
            User user = userService.getById(order.getUserId());


            return ApiResult.ok(null, "取消成功");
        } else {
            return ApiResult.fail("取消失败");
        }
    }

    @RequestMapping(value = "/virtual", method = RequestMethod.POST)
    @RequiresPermissions("/order/order/delivery")
    @OperationLog(name = "virtual")
    @ApiOperation(value = "virtual", response = String.class)
    public ApiResult<String> virtual(@Validated @RequestBody OrderVirtualParam orderVirtualParam){
        if (orderService.virtual(orderVirtualParam)) {
            return ApiResult.ok(null, "发货成功");
        } else {
            return ApiResult.fail("发货失败");
        }
    }


    @RequestMapping(value = "/deductZMXX", method = RequestMethod.POST)
    @RequiresPermissions("/order/order/delivery")
    @OperationLog(name = "芝麻授信扣款(先享,免押)")
    @ApiOperation(value = "芝麻授信扣款(先享,免押)", response = String.class)
    public ApiResult<String> deductZMXX( Integer orderId) throws AlipayApiException {
        Order order = orderService.getById(orderId);
//        List<OrderProduct> orderProductList = orderProductService.getProductList(orderPayParam.getOrderId());

        User user = userService.getById(order.getUserId());
        BigDecimal shengyudaikou = order.getPayPrice().subtract(order.getDeductionMoney());
        OrderCreditPay orderCreditPay = orderCreditPayService.getOne(new LambdaQueryWrapper<OrderCreditPay>()
                .eq(OrderCreditPay::getOrderId, order.getOrderId())
                .eq(OrderCreditPay::getPayStatus, 10)
                .orderByDesc(OrderCreditPay::getCreateTime)
                .last("limit 1"));
        String remark= DateUtil.formatDateTime(new Date()) + "系统请求扣款,金额:" + shengyudaikou+"元;<br/>";

        if (orderCreditPay == null) {
            orderCreditPay = new OrderCreditPay();
            orderCreditPay.setOrderId(orderId);
            orderCreditPay.setOutRequestNo(OrderUtils.geneOrderNo(order.getUserId()));
            orderCreditPay.setPayStatus(10);
            orderCreditPay.setPayPrice(shengyudaikou);
            orderCreditPay.setPayType(order.getPayType());//免押扣款
            orderCreditPay.setOutTradeNo(OrderUtils.geneOrderNo(order.getUserId()));
            orderCreditPay.setRemark(remark+orderCreditPay.getRemark() );

            orderCreditPayService.save(orderCreditPay);
        }else {
            orderCreditPay.setRemark(orderCreditPay.getRemark()+remark );
            orderCreditPayService.updateById(orderCreditPay);
        }
        if (order.getPayType().equals(OrderPayTypeEnum.ALIPAY_MY.getValue())) {
            AlipayTradePayResponse response = alipayUtils.tradePayMY(orderCreditPay.getOutTradeNo(), shengyudaikou, "商品", order.getCreditBizOrderId());
            orderCreditPay.setTradeNo(response.getTradeNo());
            orderCreditPayService.updateById(orderCreditPay);
        }else {
            String s = alipayUtils.tradeOrderPay(user.getOpenId(), shengyudaikou, order.getTradeNo(), orderCreditPay.getOutRequestNo());
        }

        orderCreditPayService.save(orderCreditPay);
        orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getOrderId, order.getOrderId()).set(Order::getAuthRemark, order.getAuthRemark()+remark));

        return ApiResult.ok(null, "请求扣款成功,等待支付宝结果");

    }

    @RequestMapping(value = "/getRickReport", method = RequestMethod.POST)
    @RequiresPermissions("/order/order/delivery")
    @OperationLog(name = "获取风控报告")
    @ApiOperation(value = "获取风控报告", response = String.class)
    public ApiResult<String> getRickReport( Integer orderId) throws AlipayApiException {
        Order order = orderService.getById(orderId);
        User user = userService.getById(order.getUserId());
        String url;
        if(StringUtils.isBlank(order.getBuerRiskJson())){
            JSONObject jsonObject = BuerUtil.rickReport(user.getIdName(), user.getIdNumber(), user.getMobile());
            order.setBuerRiskJson(jsonObject.toJSONString());
            orderService.update(new LambdaUpdateWrapper<Order>().in(Order::getOrderId, order.getOrderId()).set(Order::getBuerRiskJson, jsonObject.toJSONString()));
        }
        JSONObject data = JSONObject.parseObject(order.getBuerRiskJson());
        return ApiResult.ok(data.getJSONObject("resp_data").getString("url"), "获取成功");
    }


    @RequestMapping(value = "/authAudit", method = RequestMethod.POST)
    @RequiresPermissions("/order/order/delivery")
    @OperationLog(name = "先享后付审核")
    @ApiOperation(value = "先享后付审核", response = String.class)
    public ApiResult<String> authAudit(@Validated @RequestBody OrderAuthAuditParam orderVirtualParam){
        if (orderService.authAudit(orderVirtualParam)) {
            return ApiResult.ok(null, "成功");
        } else {
            return ApiResult.fail("失败");
        }
    }


}
